import redis
import json

class JobDescCache:
    """
    职位描述Redis缓存工具类（同步版，适合Django/脚本/普通流程）
    """
    def __init__(self, host='localhost', port=6379, db=1):
        self.redis = redis.Redis(host=host, port=port, db=db, decode_responses=True)

    def get_job_desc(self, job_id):
        cache_key = f"job_desc:{job_id}"
        cached_data = self.redis.get(cache_key)
        if cached_data:
            return json.loads(cached_data)
        return None

    def set_job_desc(self, job_id, desc_dict, expire=3600):
        cache_key = f"job_desc:{job_id}"
        self.redis.setex(cache_key, expire, json.dumps(desc_dict))

    def get_or_set_job_desc(self, job_id, fetch_func, expire=3600):
        """
        fetch_func: 同步函数，接收job_id，返回dict
        """
        desc = self.get_job_desc(job_id)
        if desc:
            return desc
        desc = fetch_func(job_id)
        if desc:
            self.set_job_desc(job_id, desc, expire)
        return desc

    def delete_job_desc(self, job_id):
        cache_key = f"job_desc:{job_id}"
        self.redis.delete(cache_key) 